package com.passwd.designdecrypt.decrypt;

import com.passwd.designcore.utils.FileUtils;
import com.passwd.designcore.utils.KeyUtils;
import com.passwd.designcore.utils.SMS4;


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;

public class DecryptCore {


    public String decryptRun(InputStream inputStream) {
        ArrayList<String> arrayList = FileUtils.readFile(inputStream);
        String result = "success";
        if (arrayList == null || arrayList.isEmpty()) {
            result = "error";
        }
        try {
            String[] keys = arrayList.get(0).split(",|，");
            String resultEncode = "";
            for (int i = 0; i < keys.length; i++) {
                if (i != 0) {
                    resultEncode += ",";
                }
                resultEncode = decodeWriteFile(keys[i]);
            }

            result = FileUtils.writeFile(resultEncode, KeyUtils.outputDecryptFileName);
        } catch (Exception e) {
            e.printStackTrace();
            result = "error";
        }
        return result;
    }

    /**
     * 解密文件 并写入文件
     *
     * @param key
     * @return
     */
    private String decodeWriteFile(String key) throws Exception {
        int inLen = 16, ENCRYPT = 1, DECRYPT = 0, inlen1 = 32;
        SMS4 sms4=new SMS4();
        // 第一步
        byte[] C1 = new byte[16];
        byte[] keyLeft = new byte[8];
        byte[] keyRight = new byte[8];
        getBytes(key, keyLeft, keyRight,C1);// 将key 转成byte左右数组

        // 第二步
        byte[] c1Left64=new byte[8];
        for (int i = 0; i < keyLeft.length; i++) {
            // TODO 这块的强转可以吗
            int i1 = keyLeft[i] ^ KeyUtils.S1[i];
            byte ele = (byte) (i1);//得到c1的左64比特
            c1Left64[i]=ele;
        }

        //  第三步
        byte[] K3=new byte[16];
        byte[] c1 = KeyUtils. fillZeroTo128(c1Left64);// c1的左64比特（填充至128比特）
       sms4.sms4(c1,16,KeyUtils.K2,K3,ENCRYPT); // 得到密钥K3

        //第四步
        byte[] fourResult=new byte[16];
        byte[] S1128 = KeyUtils. fillZeroTo128(KeyUtils.S1);//S1填充至128比特
        sms4.sms4(S1128,16,K3,fourResult,ENCRYPT);//输出结果取后64比特
        byte[] T1Right64 = new byte[8];
        for (int i = fourResult.length / 2; i < fourResult.length; i++) {// 输出结果取后64比特(右)
            T1Right64[i - fourResult.length / 2] = c1[i];
        }
        int S1len = KeyUtils.S1.length;
        int T1len = S1len + T1Right64.length;
        byte[] T1Init = new byte[T1len];
        for (int i = 0; (i < T1len) && i < 16; i++) { // 流密码S1和结果的后64比特拼接成T1
            if (i < S1len) {
                T1Init[i] = KeyUtils.S1[i];    // 先左拼S1
            } else {
                T1Init[i] = fourResult[i ]; // 再右拼fourResult  ；
            }
        }
        byte[] T1 = T1Init;

        // 第五步
        c1 = new byte[16];
        byte[] result = new byte[16];
        for (int i = 0; i < c1.length; i++) {
            c1[i]=(byte)(T1[i] ^ C1[i]);// 将c1和T1异或 ,得到c1
        }
        sms4.sms4(c1,16,KeyUtils.K1,result,DECRYPT);//输出结果为第一个关键词

        return new String(result);
    }

    private void getBytes(String key, byte[] keyLeft, byte[] keyRight, byte[] C1) {
        String[] split = key.split("\\.");

        for (int i = 0; i < split.length; i++) {
            C1[i]=new BigInteger(split[i], 16).byteValue();
            if(i<8){
                keyLeft[i]=C1[i];
            }else {
                keyRight[i-8]=C1[i];
            }
        }

    }
}
